<template>
  <div>
    <h1>添加抽奖活动</h1>
    <div>
      <el-form
        ref="ruleFormRef"
        style="max-width: 1200px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="活动名称" prop="name" style="width: 400px">
          <el-input
            v-model="ruleForm.activeName"
            placeholder="请输入活动名称"
          />
        </el-form-item>
        <el-form-item label="活动时间" required style="width: 500px">
          <el-date-picker
            v-model="ruleForm.activeTime"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format="A hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="参与用户" prop="resource" style="width: 400px">
          <el-radio-group v-model="ruleForm.userFlag">
            <el-radio
              v-for="item in userFlagList"
              :value="item.dictValue"
              :key="item.dectId"
              >{{ item.dictName }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动免费抽奖次数" prop="name" style="width: 400px">
          <el-input v-model="ruleForm.freeTimes" placeholder="请输入抽奖次数" />
        </el-form-item>
        <el-form-item label="规则选择" prop="name" style="width: 1000px">
          <el-table :data="ruleList" stripe style="width: 100%">
            <el-table-column prop="ruleId" label="序号" width="60" />
            <el-table-column prop="ruleImage" label="图片" width="80">
              <template #default="scope">
                <el-image
                v-if="scope.row.ruleImage"
                  :src="scope.row.ruleImage"
                  style="width: 50px; height: 50px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="ruleName" label="名称" width="100" />
            <el-table-column prop="winProd" label="奖品" width="100" />
            <el-table-column prop="winImage" label="中奖弹窗图片" width="110">
              <template #default="scope">
                <el-image
                v-if="scope.row.winImage"
                  :src="scope.row.winImage"
                  style="width: 50px; height: 50px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="prodNum" label="数量" width="80" />
            <el-table-column prop="winChance" label="奖品概率" width="80" />
            <el-table-column label="操作" />
          </el-table>
          <div>
            <el-button type="primary" size="small" @click="onAddRule"
              >添加规则</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="中奖名单" prop="delivery" style="width: 400px">
          <el-switch
            v-model="ruleForm.winFlag"
            active-text="公开"
            inactive-text="隐藏"
            :active-value="0"
            :inactive-value="1"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </el-form-item>
        <el-form-item label="中奖记录" prop="delivery" style="width: 400px">
          <el-switch
            v-model="ruleForm.winRecord"
            active-text="公开"
            inactive-text="隐藏"
            :active-value="0"
            :inactive-value="1"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </el-form-item>
        <el-form-item label="活动状态" prop="delivery" style="width: 400px">
          <el-switch
            v-model="ruleForm.activeStatus"
            :active-value="0"
            :inactive-value="1"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </el-form-item>
        <el-form-item label="活动规则" prop="delivery" style="width: 700px">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="ruleForm.activeContent"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            完成
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 添加规则 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加规则" width="500">
        <el-form :model="form">
          <el-form-item label="名称" :label-width="formLabelWidth">
            <el-input v-model="form.ruleName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="图片" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/shop/type/uploadImage"
              :show-file-list="false"
              :on-success="handleRuleImageSuccess"
              :headers="headers"
            >
              <img v-if="ruleImage" :src="ruleImage" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="奖品" :label-width="formLabelWidth">
            <el-input v-model="form.winProd" autocomplete="off" />
          </el-form-item>
          <el-form-item label="中奖弹窗图片" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/shop/type/uploadImage"
              :show-file-list="false"
              :on-success="handleWinImageSuccess"
              :headers="headers"
            >
              <img v-if="winImage" :src="winImage" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="数量" :label-width="formLabelWidth">
            <el-input v-model="form.prodNum" autocomplete="off" />
          </el-form-item>
          <el-form-item label="奖品概率" :label-width="formLabelWidth">
            <el-input v-model="form.winChance" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="onSumbitAddRule">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { getDietList,addActive } from "../api/api";
import { useRouter } from "vue-router";

const router = useRouter();

const mode = "default";

interface RuleForm {
  activeContent: string;
  activeName: string;
  activeStatus: number;
  activeTime: [];
  beginTime: string;
  endTime: string;
  freeTimes: number;
  userFlag: number;
  winFlag: number;
  winRecord: number;
  ruleList: [];
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  activeContent: "",
  activeName: "",
  activeStatus: 0,
  activeTime: [],
  beginTime: "",
  endTime: "",
  freeTimes: 0,
  ruleList: [],
  userFlag: 0,
  winFlag: 0,
  winRecord: 0,
});

const ruleList = ref<any>([]);

//上传图片
const ruleImage = ref("");
const winImage = ref("");
const headers = ref({
  token: sessionStorage.getItem("token") || "",
});
const handleRuleImageSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // ruleImage.value = URL.createObjectURL(uploadFile.raw!)
  ruleImage.value = response.data;
};
const handleWinImageSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // ruleImage.value = URL.createObjectURL(uploadFile.raw!)
  winImage.value = response.data;
};

const onAddRule = () => {
  console.log("onAddRule");
  Object.assign(form, {
    prodNum: 0,
    ruleImage: "",
    ruleName: "",
    winChance: 0,
    winImage: "",
    winProd: "",
  });
  ruleImage.value = '';
  winImage.value = '';
  dialogFormVisible.value = true;
};
const onSumbitAddRule = () => {
  console.log("onSumbitAddRule");
  const rule: any = {};
  //克隆一个对象
  Object.assign(rule, form);
  rule.ruleImage = ruleImage.value;
  rule.winImage = winImage.value;
  ruleList.value.push(rule);

  //初始化表单
  Object.assign(form, {
    prodNum: 0,
    ruleImage: "",
    ruleName: "",
    winChance: 0,
    winImage: "",
    winProd: "",
  });
  ruleImage.value = '';
  winImage.value = '';
};

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = reactive({
  prodNum: 0,
  ruleImage: "",
  ruleName: "",
  winChance: 0,
  winImage: "",
  winProd: "",
});

const rules = reactive<FormRules<RuleForm>>({
  activeName: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
});

//提交添加抽奖活动的表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      ruleForm.ruleList = ruleList.value
      addActive(ruleForm).then(res=>{
        if(res.data.code == 200){
          ElMessage.success("添加成功");
          router.push("/home/active")
        }else{
          ElMessage.error(res.data.msg);
        }
      })
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  //初始化表单
  Object.assign(form, {
    prodNum: 0,
    ruleImage: "",
    ruleName: "",
    winChance: 0,
    winImage: "",
    winProd: "",
  });

  router.push("/home/active")
};

const userFlagList = ref([]);

onMounted(() => {
  getDietList(5).then((res) => {
    if (res.data.code == 200) {
      userFlagList.value = res.data.data;
    }
  });
});

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = "<p>模拟 Ajax 异步设置内容</p>";
  }, 1500);
});

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<!-- 上传图片样式 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
